(function(window, $) {
  function initSummernote(selector, options) {
    $(document).ready(function() {
      $(selector).summernote(options);
    });
  }

  function handleImageUpload(files, obj) {
    console.log(obj, 'obj');


    var data = new FormData();
    data.append("name", files[0].name);
    data.append("file", files[0]);

    console.log('FormData content:', data);

    $.ajax({
      url: '/fast/sys/comm/upload',
      type: 'POST',
      data: data,
      cache: false,
      contentType: false,
      processData: false,
      success: function(res) {
        if (res.code === '00000') {
          $(obj).summernote('editor.insertImage', '/fast/sys/comm/download?fileId=' + res.id);
        } else {
          console.error('Upload failed with code:', res.code);
        }
      },
      error: function(data) {
        console.log('Error uploading image:', data);
      }
    });
  }
  function handleVideoInsert(url, obj) {
    console.log(url,'url')
    $(obj).summernote('editor.insertVideo', url);
  }

  // 取值
  function getContent(selector) {
    return $(selector).summernote('code');
  }
  // 赋值
  function setContent(selector, content) {
    $(selector).summernote('code', content);
  }

  function submitContent(selector) {
    var content = getContent(selector);
    console.log(content);
    return content;
  }

  // 暴露方法
  window.SummernoteComponent = {
    init: function(selector, options) {
      options.callbacks = options.callbacks || {};
      options.callbacks.onImageUpload = function(files) {
        handleImageUpload(files,this);
      };

      options.callbacks.onMediaUpload = function(files) {
        handleVideoInsert(files[0],this);
      };
      initSummernote(selector, options);
    },
    getContent: function(selector) {
      return getContent(selector);
    },
    setContent:function(selector,content){
    return setContent(selector,content);
    },
    submit: function(selector) {
      return submitContent(selector);
    }
  };

  // 添加默认初始化逻辑
  $(document).ready(function() {
    // 遍历所有需要初始化的富文本编辑器
    $('.summernote').each(function() {
      var selector = '#' + this.id;
      window.SummernoteComponent.init(selector, {
        height: 300,
        toolbar: [
          ['style', ['style']],
          ['font', ['bold', 'italic', 'underline', 'clear']],
          ['fontname', ['fontname']],
          ['fontsize', ['fontsize']],
          ['color', ['color']],
          ['para', ['ul', 'ol', 'paragraph']],
          ['table', ['table']],
          ['insert', ['link', 'picture', 'video']],
          ['view', ['fullscreen', 'codeview', 'help']]
        ],
        lang: 'zh-CN'
      });

      $('#' + this.id + '-submit').click(function() {
        var content = window.SummernoteComponent.getContent(selector);
        console.log(content);
      });
    });
  });
})(window, jQuery);